<template>
  <view class="page-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <view class="header-right"></view>
      </view>
    </view>

    <!-- 标题部分 -->
    <view class="title-section">
      <text class="title">新增求职期望</text>
      <text class="subtitle">我们会据此展示职位，并将你推荐给HR</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <view class="card-box">
        <!-- 期望职位 -->
        <view class="form-item">
          <text class="field-label">期望职位</text>
          <view class="field-wrapper" @click="goToJobTypeSelector">
            <text
              class="field-input"
              :class="{ placeholder: !formData.jobName }"
            >
              {{ formData.jobName || "请选择期望职位" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 工作城市 -->
        <view class="form-item">
          <text class="field-label">工作城市</text>
          <view class="field-wrapper" @click="goToCitySelector">
            <text class="field-input" :class="{ placeholder: !formData.city }">
              {{ formData.city || "请选择工作城市" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 薪资要求 -->
        <view class="form-item">
          <text class="field-label">薪资要求</text>
          <picker
            mode="multiSelector"
            :range="salaryRange"
            :value="selectedSalaryIndex"
            @change="onSalaryChange"
            class="salary-picker"
          >
            <view class="field-wrapper">
              <text
                class="field-input"
                :class="{ placeholder: getSalaryDisplay() === '请选择' }"
              >
                {{ getSalaryDisplay() }}
              </text>
              <image
                src="/static/icons/right-arrow-gray.png"
                class="right-arrow"
              ></image>
            </view>
          </picker>
        </view>

        <view class="line-wrapper"><view class="line"></view></view>

        <!-- 期望行业 -->
        <view class="form-item">
          <text class="field-label">期望行业</text>
          <view class="field-wrapper" @click="showIndustryPicker = true">
            <text
              class="field-input"
              :class="{ placeholder: !selectedIndustryName }"
            >
              {{ selectedIndustryName || "请选择期望行业" }}
            </text>
            <image
              src="/static/icons/right-arrow-gray.png"
              class="right-arrow"
            ></image>
          </view>
        </view>

        <!-- 保存按钮 -->
        <view class="btn-wrapper" @click="saveWorkExpectation">
          <text class="btn-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 行业选择弹窗 -->
    <view v-if="showIndustryPicker" class="industry-modal">
      <view class="modal-mask" @tap="showIndustryPicker = false"></view>
      <view class="industry-picker-popup">
        <view class="popup-header">
          <text class="popup-title">选择行业</text>
          <text class="popup-close" @tap="showIndustryPicker = false">×</text>
        </view>
        <scroll-view class="industry-list" scroll-y>
          <view
            v-for="item in topIndustryList"
            :key="item.id"
            class="industry-item"
          >
            <view class="top-industry">
              <text class="industry-name" style="color: #666">{{
                item.name
              }}</text>
              <view class="industry-actions">
                <text
                  v-if="!item.loaded || item.children.length > 0"
                  class="expand-icon"
                  @tap="toggleIndustry(item)"
                  >{{ item.expanded ? "▼" : "▶" }}</text
                >
              </view>
            </view>

            <view v-if="item.expanded" class="second-industry-list">
              <view
                v-for="child in item.children"
                :key="child.id"
                class="second-industry"
                :class="{ selected: child.selected }"
                @tap="selectIndustry(child)"
              >
                <text class="industry-name">{{ child.name }}</text>
              </view>

              <view
                v-if="item.loaded && item.children.length === 0"
                class="no-data"
              >
                暂无二级行业
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { submitWorkExpectation, getWorkExpectationDetail } from "@/api/resume";
import { getIndustryTopListApi, getChildrenIndustryApi } from "@/api/company";

// 获取路由参数
const expectationId = ref("");
const isEditMode = ref(false);

onLoad((options) => {
  if (options) {
    expectationId.value = options.id || "";
    isEditMode.value = !!expectationId.value;
  }

  // 初始化数据
  initSalaryRange();
  loadIndustryData();

  // 如果是编辑模式，加载数据
  if (isEditMode.value && expectationId.value) {
    loadExpectationDetail();
  }
});

// 表单数据
const formData = ref({
  resumeId: "",
  id: "",
  jobName: "",
  jobType: "",
  jobTypeId: "",
  city: "",
  industry: "",
  beginSalary: 0,
  endSalary: 0,
});

// 薪资选项
const salaryRange = ref([[], []]);
const selectedSalaryIndex = ref([0, 0]);

// 行业数据
const topIndustryList = ref([]);
const industryCache = ref({});
const selectedIndustryName = ref("");
const showIndustryPicker = ref(false);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 跳转到职位类别选择页面
const goToJobTypeSelector = () => {
  const currentJobType = {
    jobType: formData.value.jobType,
    jobTypeId: formData.value.jobTypeId,
  };
  uni.setStorageSync("currentJobType", currentJobType);

  uni.navigateTo({
    url: "/pages/common/jobTypeSelector",
  });
};

// 跳转到城市选择页面
const goToCitySelector = () => {
  uni.setStorageSync("currentCity", formData.value.city);

  uni.navigateTo({
    url: "/pages/company/citySelector",
  });
};

// 薪资选择变化
const onSalaryChange = (e) => {
  const newIndexes = e.detail.value;
  const startSalary = salaryRange.value[0][newIndexes[0]];
  const endSalary = salaryRange.value[1][newIndexes[1]];

  if (startSalary && endSalary) {
    const startValue = parseInt(startSalary.replace("K", ""));
    const endValue = parseInt(endSalary.replace("K", ""));

    // 检查薪资范围是否合理
    if (startValue >= endValue) {
      uni.showToast({
        title: `起始薪资${startValue}K不能大于等于结束薪资${endValue}K`,
        icon: "none",
        duration: 2500,
      });
      return; // 不更新选择
    }

    selectedSalaryIndex.value = newIndexes;
    formData.value.beginSalary = startValue;
    formData.value.endSalary = endValue;

    console.log(`薪资范围已更新: ${startValue}K - ${endValue}K`);
  }
};

// 获取薪资显示文本
const getSalaryDisplay = () => {
  if (formData.value.beginSalary && formData.value.endSalary) {
    return `${formData.value.beginSalary}-${formData.value.endSalary}K`;
  }
  return "请选择";
};

// 初始化薪资选项
const initSalaryRange = () => {
  // 起始薪资（1K起）
  const startSalaryArr = [];
  for (let i = 1; i <= 199; i++) {
    if (i <= 30) {
      startSalaryArr.push(i + "K");
    } else if (i <= 100 && i % 5 === 0) {
      startSalaryArr.push(i + "K");
    } else if (i > 100 && i % 10 === 0) {
      startSalaryArr.push(i + "K");
    }
  }

  // 结束薪资（2K起，保证比起始薪资大）
  const endSalaryArr = [];
  for (let i = 2; i <= 200; i++) {
    if (i <= 30) {
      endSalaryArr.push(i + "K");
    } else if (i <= 100 && i % 5 === 0) {
      endSalaryArr.push(i + "K");
    } else if (i > 100 && i % 10 === 0) {
      endSalaryArr.push(i + "K");
    }
  }

  salaryRange.value = [startSalaryArr, endSalaryArr];
};

// 加载一级行业数据
const loadIndustryData = async () => {
  try {
    const data = await getIndustryTopListApi();
    topIndustryList.value = (data || [])
      .sort((a, b) => (a.sort || 0) - (b.sort || 0))
      .map((item) => ({
        ...item,
        children: [],
        expanded: false,
        loaded: false,
      }));
  } catch (error) {
    uni.showToast({
      title: "加载行业数据失败",
      icon: "none",
    });
  }
};

// 加载二级行业数据
const loadSecondIndustry = async (parentItem) => {
  const topIndustryId = parentItem.id;
  if (industryCache.value[topIndustryId]) {
    parentItem.children = industryCache.value[topIndustryId];
    parentItem.loaded = true;
    return;
  }

  try {
    const data = await getChildrenIndustryApi(topIndustryId);
    const secondList = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
    parentItem.children = secondList;
    parentItem.loaded = true;
    industryCache.value[topIndustryId] = secondList;
  } catch (error) {
    uni.showToast({
      title: "加载二级行业失败",
      icon: "none",
    });
  }
};

// 行业选择相关方法
const toggleIndustry = async (item) => {
  item.expanded = !item.expanded;
  if (item.expanded && !item.loaded) {
    await loadSecondIndustry(item);
  }
};

const selectIndustry = (industry) => {
  formData.value.industry = industry.name;
  selectedIndustryName.value = industry.name;
  showIndustryPicker.value = false;

  // 重置所有选中状态
  topIndustryList.value.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => (child.selected = false));
    }
  });
  industry.selected = true;
};

// 加载求职期望详情（编辑模式）
const loadExpectationDetail = async () => {
  try {
    const data = await getWorkExpectationDetail(expectationId.value);
    if (data) {
      formData.value = {
        ...formData.value,
        ...data,
      };
      console.log("111", formData.value);

      // 设置显示值
      selectedIndustryName.value = data.industry || "";

      // 设置薪资索引
      updateSalaryIndexes();
    }
  } catch (error) {
    uni.showToast({
      title: "获取求职期望详情失败",
      icon: "none",
    });
  }
};

// 更新薪资选中索引
const updateSalaryIndexes = () => {
  if (formData.value.beginSalary && formData.value.endSalary) {
    const startIndex =
      salaryRange.value[0]?.findIndex(
        (item) => parseInt(item.replace("K", "")) === formData.value.beginSalary
      ) || 0;

    const endIndex =
      salaryRange.value[1]?.findIndex(
        (item) => parseInt(item.replace("K", "")) === formData.value.endSalary
      ) || 0;

    selectedSalaryIndex.value = [startIndex, endIndex];
  }
};

// 保存求职期望
const saveWorkExpectation = async () => {
  // 表单验证
  if (!formData.value.jobName) {
    uni.showToast({
      title: "请选择期望职位",
      icon: "none",
    });
    return;
  }

  if (!formData.value.city) {
    uni.showToast({
      title: "请选择工作城市",
      icon: "none",
    });
    return;
  }

  if (!formData.value.beginSalary || !formData.value.endSalary) {
    uni.showToast({
      title: "请选择薪资要求",
      icon: "none",
    });
    return;
  }

  if (formData.value.beginSalary >= formData.value.endSalary) {
    uni.showToast({
      title: "请选择合适的薪资范围",
      icon: "none",
    });
    return;
  }

  if (!formData.value.industry) {
    uni.showToast({
      title: "请选择期望行业",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "保存中...",
    });

    // 准备提交数据
    const submitData = {
      resumeId: formData.value.resumeId,
      jobName: formData.value.jobName,
      jobType: formData.value.jobType,
      city: formData.value.city,
      industry: formData.value.industry,
      beginSalary: formData.value.beginSalary,
      endSalary: formData.value.endSalary,
    };

    // 如果是编辑模式，添加ID
    if (isEditMode.value && expectationId.value) {
      submitData.id = expectationId.value;
    }

    await submitWorkExpectation(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });

    // 通知简历页面刷新数据
    uni.$emit("refreshResume");

    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败",
      icon: "none",
    });
  }
};

// 页面显示时处理返回数据
const handleOnShow = () => {
  // 获取选择的城市
  const selectedCity = uni.getStorageSync("selectedCity");
  if (selectedCity) {
    formData.value.city = selectedCity;
    uni.removeStorageSync("selectedCity");
  }

  // 获取选择的职位类别
  const selectedJobType = uni.getStorageSync("selectedJobType");
  if (selectedJobType) {
    formData.value.jobName = selectedJobType.name || selectedJobType.fullPath;
    formData.value.jobType = selectedJobType.name || selectedJobType.fullPath;
    formData.value.jobTypeId = selectedJobType.id;
    uni.removeStorageSync("selectedJobType");
  }
};

// 页面加载
onMounted(() => {
  // 监听城市选择事件
  uni.$on("citySelected", (city) => {
    formData.value.city = city.city || city;
  });

  // 监听职位类别更新事件
  uni.$on("updateJobType", (value) => {
    formData.value.jobName = value.name || value;
    formData.value.jobType = value.name || value;
    if (value.id) {
      formData.value.jobTypeId = value.id;
    }
  });

  handleOnShow();
});

// uni-app页面生命周期 - 页面显示时触发
function onShow() {
  handleOnShow();
}

// 页面卸载时移除事件监听器
onUnmounted(() => {
  uni.$off("citySelected");
  uni.$off("updateJobType");
});

// 暴露生命周期函数
defineExpose({
  onShow: handleOnShow,
});
</script>

<style scoped lang="less">
.page-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-right {
  width: 60rpx;
}

/* 标题部分 */
.title-section {
  padding: 40rpx 40rpx 20rpx;
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.title {
  font-size: 48rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.2;
}

.subtitle {
  font-size: 28rpx;
  color: #999999;
  line-height: 1.4;
}

/* 表单内容样式 */
.form-content {
  flex: 1;
  background-color: #ffffff;
}

.card-box {
  padding: 20rpx 40rpx 40rpx;
  display: flex;
  flex-direction: column;
}

.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 40rpx;
}

.field-label {
  font-size: 32rpx;
  color: #333333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.field-wrapper {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  min-height: 44rpx;
}

.field-input {
  font-size: 36rpx;
  color: #333333;
  flex: 1;
  line-height: 1.4;
}

.placeholder {
  color: #b5bdbd;
}

.right-arrow {
  width: 36rpx;
  height: 36rpx;
  margin-left: 20rpx;
  flex-shrink: 0;
}

.line-wrapper {
  margin: 40rpx 0;
}

.line {
  width: 100%;
  height: 1rpx;
  background-color: #f0f0f0;
}

/* 薪资选择器样式 */
.salary-picker {
  width: 100%;
}

/* 保存按钮 */
.btn-wrapper {
  margin-top: 120rpx;
  width: 100%;
  height: 92rpx;
  border-radius: 12rpx;
  background-color: #00bdb4;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.btn-text {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 500;
}

/* 行业选择弹窗样式 */
.industry-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.industry-picker-popup {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
  padding: 0 20rpx;
}

.industry-list {
  max-height: 70vh;
}

.industry-item {
  border-bottom: 1rpx solid #f5f5f5;
}

.top-industry {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #fafafa;
}

.industry-name {
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.top-industry .industry-name {
  color: #666;
  font-weight: bold;
}

.industry-actions {
  margin-left: 20rpx;
}

.expand-icon {
  color: #999;
  font-size: 24rpx;
}

.second-industry-list {
  background: #fff;
}

.second-industry {
  padding: 25rpx 30rpx 25rpx 60rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.second-industry:last-child {
  border-bottom: none;
}

.second-industry.selected {
  background: #e6f7ff;
}

.second-industry .industry-name {
  font-size: 28rpx;
  color: #666;
}

.no-data {
  padding: 30rpx 60rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>